﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pb;
public class PDKGameOver : MonoBehaviour {

    EginUser user = EginUser.Instance;
    EginPDK pdk = EginPDK.Instance;

    //bg
    public GameObject winBg;
    public GameObject loseBg;
    //btn

    public GameObject Collider;
    public RunGameOverBroadcast newpb;

    //lable
    public List<UILabel> names;
    public List<UILabel> scores;
    public UILabel cardsCount;
    public List<UISprite> allCloseSprites;  
    public List<UISprite> winSprites;

    public List<GameObject> ScoreFather;
    public List<GameObject> Score;
    public List<UISprite> jiaJian;
    public List<GameOverUserInfo> gameOverUserInfo;
    public List<PDKUser> pdkUsers;

    public bool nextover1;
    void Awake()
    {

        //UIEventListener.Get(LeaveGameBtn).onClick = ButtonClick;
        UIEventListener.Get(Collider).onClick = ButtonClick;
        for (int i = 0; i < 3;i++ )
        {
            pdkUsers[i] = GameObject.Find("UI Root/PDKGamePanel/AllPlayers/Player" + (i + 1)).GetComponent<PDKUser>();
        }

    }
    private void Start()
    {
        StartCoroutine(des());
        //if (user.ControlScene == 1)
        {
            //LeaveGameBtn.SetActive(false);
            //ContinueGameBtn.transform.localPosition = new Vector3(4, -265, 0);
        }
        //else
        {
            //显示一局结束之后各个玩家的得分情况
            #region
            //重新确定游戏结束时玩家的排列
            List<int> newList = ReConfirmUserSeatId();
            List<GameOverUserInfo> newGameOverUserList = new List<GameOverUserInfo>();
            for (int i = 0; i < newList.Count; i++)
            {
                for (int j = 0; j < gameOverUserInfo.Count; j++)
                {
                    if (gameOverUserInfo[j].SeatId == newList[i])
                    {
                        newGameOverUserList.Add(gameOverUserInfo[j]);
                    }
                }
            }

            for (int i = 0; i < newGameOverUserList.Count; i++)
            {
                if (newGameOverUserList[i].SeatStatus == SEAT_STATUS.GameSit)
                {
                    int tempIndex = pdk.returnOtherSeatIndex(newGameOverUserList[i].SeatId);

                    int tempScore = newGameOverUserList[i].RoundScore;

                    string tempStr = user.ReturnMoney(Mathf.Abs(newGameOverUserList[i].RoundScore));

                    float x = Score[tempIndex].transform.localPosition.x;
                    float y = Score[tempIndex].transform.localPosition.y;
                    if (tempScore > 0)
                    {
                        jiaJian[tempIndex].gameObject.SetActive(true);
                        jiaJian[tempIndex].spriteName = "jia+";
                        int len = tempStr.Length;
                        for (int j = 0; j < len; j++)
                        {
                            GameObject obj = (GameObject)Instantiate(Score[tempIndex]);
                            obj.SetActive(true);
                            obj.transform.parent = ScoreFather[tempIndex].transform;
                            obj.transform.localScale = new Vector3(1, 1, 1);
                            string str = tempStr.Substring(0, 1);
                            if (j == 0)
                            {
                                obj.transform.localPosition = new Vector3(x, y, 0);
                            }
                            else
                            {
                                if (str == ".")
                                {
                                    x += 20;
                                }
                                else if (str == "w")
                                {
                                    x += 30;
                                }
                                else
                                {
                                    x += 25;
                                }
                                obj.transform.localPosition = new Vector3(x, y, 0);
                            }
                            tempStr = tempStr.Remove(0, 1);
                            UISprite spri = obj.GetComponent<UISprite>();
                            spri.spriteName = "jia" + str;
                            if(spri.spriteName == "jia."){                                
                                spri.width = spri.GetAtlasSprite().width;
                                spri.height = spri.GetAtlasSprite().height;
                            }
                            
                        }
                    }
                    else
                    {
                        jiaJian[tempIndex].gameObject.SetActive(true);
                        jiaJian[tempIndex].spriteName = "less-";
                        int len = tempStr.Length;
                        for (int j = 0; j < len; j++)
                        {
                            GameObject obj = (GameObject)Instantiate(Score[tempIndex]);
                            obj.SetActive(true);
                            obj.transform.parent = ScoreFather[tempIndex].transform;
                            obj.transform.localScale = new Vector3(1, 1, 1);
                            string str = tempStr.Substring(0, 1);
                            if (j == 0)
                            {
                                obj.transform.localPosition = new Vector3(x, y, 0);
                            }
                            else
                            {
                                if (str == ".")
                                {
                                    x += 20;                                  
                                }
                                else if (str == "w")
                                {
                                    x += 30;
                                }
                                else
                                {
                                    x += 25;
                                }
                                obj.transform.localPosition = new Vector3(x, y, 0);
                            }
                            tempStr = tempStr.Remove(0, 1);
                            UISprite spri = obj.GetComponent<UISprite>();
                            spri.spriteName = "less" + str;
                            if (spri.spriteName == "less.")
                            {                                
                                spri.width = spri.GetAtlasSprite().width;
                                spri.height = spri.GetAtlasSprite().height;
                            }
                        }
                    }
                }
            }
        }
       #endregion
     }
            
  
    void ButtonClick(GameObject button)
    {       
        if (button.name == "Collider")
        {                     
            //销毁上局所有状态
            Destroy(GameObject.Find("PDKCards"));
            PDKGame pdkGame = GameObject.Find("Camera").GetComponent<PDKGame>();
            EginPDK pdk = EginPDK.Instance;
            for (int i = 0; i < user.gameUserInfoList.Count;i++ )
            {
                //隐藏分数 胜利图标
                int tempIndex = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                ScoreFather[tempIndex].SetActive(false);
                pdkGame.pdkUsers[i].WinSpriteObj.SetActive(false);
                pdkUsers[tempIndex].WinSpriteObj.SetActive(false);
            }
            //显示准备 换桌按钮
            GamePDKPanel gamePDKPanel = GameObject.Find("UI Root/PDKGamePanel/").GetComponent<GamePDKPanel>();
            if(user.ControlScene == 1){
                Debug.Log("好友场只显示准备按钮");
                gamePDKPanel.PrepareGreenBtn.SetActive(true);
                gamePDKPanel.PrepareGreenBtn.transform.localPosition = new Vector3(0,-62,0);
            }
            else
            {
                Debug.Log("好友场显示准备 换桌按钮");
                gamePDKPanel.PrepareGreenBtn.SetActive(true);
                gamePDKPanel.ChangeTableOrangeBtn.SetActive(true);
            }
            
            //销毁自身
            Destroy(gameObject);
        }

    }

    public void GameoverEvent(bool nextOver, List<GameOverUserInfo> gameOverUserInfo)
    {

        if (!nextOver)
        {
            //结算界面
            //EveryRound.SetActive(false);
            GameObject PDKSettlement = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load(GamePDKPrefabPath.Settlement))); //结算界面
            PDKSettlement.GetComponent<PDKSettlement>().LoadInfo(gameOverUserInfo);
        }
        else
        {
            #region 游戏结束显示
            //重新确定游戏结束时玩家的排列
            List<int> newList = ReConfirmUserSeatId();
            List<GameOverUserInfo> newGameOverUserList = new List<GameOverUserInfo>();
            for (int i = 0; i < newList.Count;i++ )
            {
                for (int j = 0;j < gameOverUserInfo.Count;j++ )
                {
                    if(gameOverUserInfo[j].SeatId == newList[i]){
                        newGameOverUserList.Add(gameOverUserInfo[j]);
                        Debug.Log("输赢牌：" + gameOverUserInfo[j].WinCardNum);
                    }
                    
                }
                Debug.Log(newGameOverUserList[i].RoundScore + "----------" + newGameOverUserList[i].SeatId);
            }

            for (int i = 0; i < newGameOverUserList.Count; i++)
            {
                for (int j = 0; j < user.gameUserInfoList.Count;j++ )
                {
                    if(newGameOverUserList[i].SeatId == user.gameUserInfoList[j].SeatId){
                        //显示名称
                        names[i].text = user.gameUserInfoList[j].Nickname;
                    }                   
                }
               
                //显示分数                               
                if (newGameOverUserList[i].RoundScore > 0)
                {
                    scores[i].text = "+" + user.ReturnMoney(newGameOverUserList[i].RoundScore);
                    scores[i].color = Color.yellow;
                    //自己赢显示胜利界面
                    if(i == 0){
                        winBg.SetActive(true);
                        loseBg.SetActive(false);
                        //显示赢牌数                       
                        cardsCount.text = Mathf.Abs(newGameOverUserList[i].WinCardNum).ToString();                                             
                    }
                    else 
                    {
                        //胜利
                        winSprites[i - 1].gameObject.SetActive(true);
                        pdkUsers[i].WinSpriteObj.SetActive(true);
                    }
                }
                else if (newGameOverUserList[i].RoundScore <= 0)
                {
                    if(newGameOverUserList[i].RoundScore == 0){
                        scores[i].text = "-" + user.ReturnMoney(newGameOverUserList[i].RoundScore);
                    }else{
                        scores[i].text = user.ReturnMoney(newGameOverUserList[i].RoundScore);
                    }
                    
                    //自己输显示失败界面
                    if (i == 0)
                    {
                        winBg.SetActive(false);
                        loseBg.SetActive(true);
                        //显示输牌（包括因为炸弹输的牌）
                        if (newGameOverUserList[i].WinCardNum == 1)
                        {
                            cardsCount.text = "0";
                        }
                        else
                        {
                            cardsCount.text = Mathf.Abs(newGameOverUserList[i].WinCardNum).ToString();
                        }
                        
                    }
                    //全关
                    if (newGameOverUserList[i].HandCardList.Count == 16)
                    {
                        allCloseSprites[i].gameObject.SetActive(true);
                    }
                }                
            }
            #endregion
            //根据不同的界面调整label位置
            //胜利界面
            if(winBg.activeSelf == true){               
                scores[0].transform.localPosition = new Vector3(-8, 20, 0);
                scores[1].transform.localPosition = new Vector3(-93, -169, 0);
                scores[2].transform.localPosition = new Vector3(-210, -169, 0);
                cardsCount.transform.localPosition = new Vector3(9, -41, 0);
            }
            else if(loseBg.activeSelf == true)
            {
                scores[0].transform.localPosition = new Vector3(-8,28,0);
                scores[1].transform.localPosition = new Vector3(-93, -169, 0);
                scores[2].transform.localPosition = new Vector3(-210, -169, 0);
                cardsCount.transform.localPosition = new Vector3(7,-38,0);
            }


            //游戏结束时清空不在房间的玩家
            PDKGame pdkgame = GameObject.Find("Camera").GetComponent<PDKGame>();
            for (int i = 0; i < gameOverUserInfo.Count; i++)
            {
                if (gameOverUserInfo[i].SeatStatus == SEAT_STATUS.Leave && user.ControlScene == 2)
                {
                    for (int j = 0; j < user.gameUserInfoList.Count; j++)
                    {
                        user.gameUserInfoList[j].IsWitness = false;
                        if (gameOverUserInfo[i].SeatId == user.gameUserInfoList[j].SeatId)
                        {
                            user.gameUserInfoList.RemoveAt(j);
                            int tempIndex = EginPDK.Instance.returnOtherSeatIndex(gameOverUserInfo[i].SeatId);
                            pdkgame.pdkUsers[tempIndex].gameObject.SetActive(false);
                            break;
                        }
                    }
                }
            }
        }
    }
    void LogMsg()
    {
        GameObject logMsg = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("LogMsg")));
    }

    IEnumerator des()
    {

        yield return new WaitForSeconds(10f);
        if (nextover1)
        {
            //销毁上局所有状态
            Destroy(GameObject.Find("PDKCards"));
            PDKGame pdkGame = GameObject.Find("Camera").GetComponent<PDKGame>();
            EginPDK pdk = EginPDK.Instance;
            for (int i = 0; i < user.gameUserInfoList.Count; i++)
            {
                //隐藏分数 胜利图标
                int tempIndex = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                ScoreFather[tempIndex].SetActive(false);
                pdkGame.pdkUsers[i].WinSpriteObj.SetActive(false);
                pdkUsers[tempIndex].WinSpriteObj.SetActive(false);
            }
            //显示准备 换桌按钮
            GamePDKPanel gamePDKPanel = GameObject.Find("UI Root/PDKGamePanel").GetComponent<GamePDKPanel>();
            gamePDKPanel.PrepareGreenBtn.SetActive(true);
            gamePDKPanel.ChangeTableOrangeBtn.SetActive(true);
            Destroy(gameObject);
        }

        for (int i = 0; i < pdkUsers.Count;i++ )
        {
            //隐藏胜利图标
            pdkUsers[i].WinSpriteObj.SetActive(false);
        }
    }

  
    /// <summary>
    /// 游戏结束时重新确定SeatId的排列
    /// </summary>
    /// <returns></returns>
    private List<int> ReConfirmUserSeatId()
    {
        int ownSeatId = pdk.seatId;
        int leftSeatId = 0;
        int rightSeatId = 0;
        List<int> seatIdList = new List<int>();
        if(ownSeatId == 1){
            leftSeatId = 3;
            rightSeatId = 2;
        }
        else if(ownSeatId == 2){
            leftSeatId = 1;
            rightSeatId = 3;
        }
        else if(ownSeatId == 3){
            leftSeatId = 2;
            rightSeatId = 1;
        }

        seatIdList.Add(ownSeatId);
        seatIdList.Add(rightSeatId);
        seatIdList.Add(leftSeatId);
        return seatIdList;
    }
}
